package com.sinaapp.gavinzhang.webserver;

import javax.servlet.Servlet;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * Created by gavin on 15-8-14.
 */
public class ServletProcessor {

    public void process(Request request,Response response){
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        ClassLoader loader = null;
        try {
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File classPath = new File(System.getProperty("user.dir")+"/target/classes/com/sinaapp/Ssgavinzhang/webserver");
            System.out.println(classPath);
            String repository = (new URL("file",null,classPath.getCanonicalPath()+File.separator)).toString();
            urls[0] = new URL(null,repository,streamHandler);
            loader = new URLClassLoader(urls);
        }catch (Exception e){
            e.printStackTrace();
        }

        Class myclass= null;
        try {
            //myclass = loader.loadClass(servletName);
            myclass = Class.forName("com.sinaapp.gavinzhang.webserver."+servletName);
        }catch (Exception e){
            e.printStackTrace();
        }

        Servlet servlet = null;

        try {
            servlet = (Servlet)myclass.newInstance();
            servlet.service(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
